package com.crealth.job;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.crealth.Config;
import com.crealth.crmserver.SessionManager;
import com.crealth.db.ClienteleDb;
import com.crealth.db.ConsumerDb;
import com.crealth.manager.SipAccountManager;
import com.crealth.memcached.ConsumerCached;
import com.crealth.model.ConsumerInfoModel;
import com.crealth.utils.StringUtil;

public class TodayEndJob implements Job {
	private static Logger logger = Logger.getLogger("running_log");
	public static Map<Integer, Long> heartbeatMap = 
			new ConcurrentHashMap<Integer, Long>();
	
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");  
        Date date = new Date();  
        String strToday = f.format(date);
        strToday += " %";
		List<ConsumerInfoModel> consumerls = ConsumerDb.selectTodaySubmitConsumer(strToday);
		for (ConsumerInfoModel consumer : consumerls) {
			int consumerID = consumer.getId();
			ConsumerCached.updateSendBackConsumer(consumerID);
		}
		
		// 重置  没有呼叫的号码
		ClienteleDb.updateClearNotCallFromGroupCallMobi();
		
		if (Config.recycleConsumer == 1) {
			recycleConsumer();
		}
		
		SessionManager.removeOutlineBoradSession();
		
		SipAccountManager.dispatchSipAccount();
	}
	
	//  跟进间隔   超过30天的   且不是 公司成交、本人成交的   收回系统分配
	public static void recycleConsumer() {
		Long curtm = System.currentTimeMillis();
    	Long ltm = curtm - Config.recycleConsumerDay*StringUtil.oneDayMillisecond;
    	Timestamp ltTm = new Timestamp(ltm);
		List<Integer> consumerIDls = ConsumerDb.selectFollowupGTTm(ltTm);
		if (consumerIDls == null || consumerIDls.size() == 0) {
			return;
		}
		Map<Integer, Integer> consumerIDMap = new HashMap<Integer, Integer>();
		for (Integer tempID : consumerIDls) {
			consumerIDMap.put(tempID, 1);
		}
		Integer maxConsumerID = ConsumerDb.selectMaximumConsumerID();
		int recycleNum = 0;
		for (int consumerID = 1; consumerID <= maxConsumerID; ++consumerID) {			
			if ( !consumerIDMap.containsKey(consumerID) ) {
				ConsumerInfoModel consumerInfo = ConsumerCached.selectConsumer(consumerID);
				if (consumerInfo == null) {
					continue;
				}
				if (consumerInfo.getUserID() == 0) {
					continue;
				}				
				String strType = consumerInfo.getCliType();
				if (strType.indexOf("分配") >= 0) {
					continue;
				}
				//  非  本人成交、公司成交
				if (strType.indexOf("成交") < 0) {
					ConsumerCached.updateConsumerUserByID(consumerID, 0, strType);
					recycleNum++;
				}
			}
		}
		
		logger.info("recycleNum: " + recycleNum);
	}	
	
}
